import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
    {
        path: '/',
        redirect: '/index'
    },
    {
        path: '/index',
        name: 'Index',
        component: () => import('../views/Index.vue'),
        children: [
            {
                path: 'player',
                name: 'Player',
                component: () => import('../views/Player.vue'),
            },
            {
                path: 'match',
                name: 'Match',
                component: () => import('../views/Match.vue'),
            },
            {
                path: 'info/:id',
                name: 'Info',
                component: () => import('../views/Info.vue'),
            }
        ]
    },
    {
        path: '/user',
        name: 'User',
        component: () => import('../views/User.vue'),
    },
]

const router = createRouter({
    // 使用hash方式实现路由
    history: createWebHashHistory(),
    routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
    // 判断是否要去登录页面
    if (to.path == '/user') {
        // 放行
        next()
    } else {
        // 去其他路由页面，判断是否有登录的token
        const token = localStorage.getItem('token')
        // 如果没有token(未登录)
        if (!token) {
            // 强制进入登录页面
            next('/user')
        } else {
            // 放行
            next()
        }
    }
})

export default router